package utils

import (
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

// 用户信息类，作为生成token的参数
type UserClaims struct {
	UserId   string `json:"userId"`
	Username string `json:"username"`
	jwt.RegisteredClaims
}

var (
	secretKey = []byte("your-secret-key") // 实际应用中应从环境变量或配置中读取
)

func GenerateToken1(userId string) (string, error) {
	claims := jwt.MapClaims{
		"sub": userId,                                // 用户唯一标识
		"exp": time.Now().Add(time.Hour * 24).Unix(), // 过期时间（24小时后）
		"iat": time.Now().Unix(),                     // 签发时间
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(secretKey)
}

func GenerateToken(claims *UserClaims) (string, error) {
	claims.RegisteredClaims = jwt.RegisteredClaims{
		ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
		Issuer:    "签发者",
		Subject:   "主题:https://liuyunshengsir.blog.csdn.net/",
		IssuedAt:  jwt.NewNumericDate(time.Now()),
		NotBefore: jwt.NewNumericDate(time.Now()),
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(secretKey)
}

func ParseToken(tokenString string) (*jwt.Token, error) {
	return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return secretKey, nil
	})
}

func main() {

	jsonWebToken, _ := GenerateToken1("123")
	fmt.Println(jsonWebToken)

	UserClaims := &UserClaims{
		UserId:   "123",
		Username: "liuyunshengsir",
	}
	jsonWebToken, _ = GenerateToken(UserClaims)
	fmt.Println(jsonWebToken)
}
